//
//  XLTabBar.swift
//  SinaWeibo
//
//  Created by 李凯 on 16/8/30.
//  Copyright © 2016年 kevin. All rights reserved.
//

import UIKit

class XLTabBar: UITabBar {
    
    //定义一个闭包属性
    var composeBtnClosure: (() -> ())?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置按钮的自动布局
    override func layoutSubviews() {
        super.layoutSubviews()
        //设置composeBtn的位置
        composeButton.center = CGPoint(x: self.frame.width * 0.5, y: self.frame.height * 0.5)
        //设置每个条目的宽度
        let itemW = self.frame.width / 5
        //遍历全部按钮
        //定义一个当前遍历到的按钮的索引
        var index = 0
        for subView in self.subviews {
            //判断是否是UITabBarButton类型
            if subView.isKind(of: NSClassFromString("UITabBarButton")!) {
                let itemX = CGFloat(index) * itemW
                //设置宽度
                subView.frame.size.width = itemW
                //设置x
                subView.frame.origin.x = itemX
                //自增
                index = index + 1
                //如果发现是第二个按钮 就往后错一个
                if index == 2 {
                    index = index + 1
                }
            }
        }
    }
    
    func setupUI() {
        //设置背景图片
        backgroundImage = #imageLiteral(resourceName: "tabbar_background")
        //将按钮添加到视图
        addSubview(composeButton)
    }
    
    //懒加载一个btn
    lazy var composeButton: UIButton = {
        let btn = UIButton()
        //添加按钮的点击事件
        btn.addTarget(self, action: #selector(composeBtnClick), for: .touchUpInside)
        //设置按钮默认/选中的背景图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        //设置按钮图标
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        //设置btn大小
        btn.sizeToFit()
        return btn
    }()
    
    @objc private func composeBtnClick() {
        composeBtnClosure?()
    }


}
